'use strict'

###*
 # @ngdoc service
 # @name xoceanApp.subject
 # @description
 # # subject
 # Service in the xoceanApp.
###
angular.module('xoceanApp')
  .value 'subjectPrototype', """
    <!doctype html>
    <html>
      <head>
        <title><%=modelname%></title>
        <meta charset="utf-8">
        <meta name="Keywords" content="<%=keywords%>">
        <meta name="Description" content="<%=digest%>">
        <style>
          .ntes-hide{
            display: none !important;
          }
          .ntes-html{
            text-align: left !important;
          }
        </style>
        <link rel="stylesheet" href="http://img3.cache.netease.com/cnews/css07/style.css">
        <link rel="stylesheet" href="http://img3.cache.netease.com/utf8/xocean/styles/xocean.css?t=#{Date.now()}">
        <script type="text/javascript" src="http://img3.cache.netease.com/cnews/js/ntes_jslib_1.x.js"></script>
        <script type="text/javascript" src="http://img3.cache.netease.com/utf8/xocean/libs/jquery-1.11.1.min.js"></script>
        <script>
          var $j = jQuery.noConflict();
          $j(document).delegate(".aside-4 .indicator span","mouseenter",function(){var b=$j(this);var c=+b.attr("data-target")-1;b.addClass("current").siblings().removeClass("current");var a=b.parents(".aside-4").find("li:eq("+c+")");a.addClass("current").siblings().removeClass("current")});
          $j(document).on("click",".photoset-5 .js-control",function(f){f.preventDefault();var d=$j(this);var a=d.parent().find("ul");var g=+d.attr("data-distance");var c=a.width();var b=a.position().left+g;if(g>0&&b>0){b=0}if(g<0&&-b+1000>c){b=1000-c}a.css({left:b+"px"})});
        </script>

      </head>
      <body data-desc="<%=digest%>">
        <%=html%>
      </body>
    </html>
  """
  .service 'Subject', ($q, $http, $location, subjectPrototype, BackendUrl)->

    microTmpl = (->
      #http://ejohn.org/blog/javascript-micro-templating/
      tmpl = (str, data) ->
        if str
          #W大写，可以匹配任何一个字母或者数字或者下划线以外的字符
          fn = (if not /\W/.test(str) then cache[str] = cache[str] or tmpl(str) else new Function("obj", "var p=[],print=function(){p.push.apply(p,arguments);};" + "with(obj){p.push('" + str.replace(/[\r\t\n]/g, " ").split("<%").join("\t").replace(/((^|%>)[^\t]*)'/g, "$1\r").replace(/\t=(.*?)%>/g, "',$1,'").split("\t").join("');").split("%>").join("p.push('").split("\r").join("\\'") + "');}return p.join('');"))
          return (if data then fn(data) else fn)
        return
      cache = {}
      tmpl
    )()
    getHtml = (str)->
      return str.match(/<body[^>]*>([\s\S]+?)<\/body>/)?[1]

    getBasicInfo = (str)->
      return angular.fromJson("{#{str.match(/.*<%=([\s\S]+?)%>/)[1]}}")


    # 删除localStorage中的subject
    deleteSubjectInLocal = (id)->
      subjects = JSON.parse localStorage.getItem('subjects')
      subjects = [] unless subjects
      _subjects = []
      for sub in subjects
        if sub.modelid isnt id
          _subjects.push sub
        else
          localStorage.removeItem(id)
      
      localStorage.setItem 'subjects', JSON.stringify(_subjects)
      if _subjects.length is subjects.length
        return {result: 0}
      else
        return {result: 1}

    # 向localStorage中保存subject
    saveSubjectToLocal = (subject)->
      subjects = JSON.parse localStorage.getItem('subjects')
      now = Date.now()
      subjects = [] unless subjects
      _subjects = []
      for sub,i in subjects
        if sub.modelid isnt subject.modelid
          _subjects.push {modelid: sub.modelid, time: now}
      if not localStorage.getItem(subject)
        _subjects.push {modelid: subject.modelid, time: now}
      subject.postime = now
      localStorage.setItem subject.modelid, JSON.stringify(subject)
      localStorage.setItem 'subjects', JSON.stringify(_subjects)

    # 获取已发布所有专题
    this.getPublishedSubjects = ->
      defer = $q.defer()
      url = "#{BackendUrl}special&action=getList"
      $http.get(url)
        .success (data)->
          for sub, i in data
            sub.postime = Date.parse(sub.postime)
          defer.resolve(data)
          return
      return defer.promise

    # 获取未发布专题
    # 保存在localstorage中
    # 超过48小时的专题会被删除
    this.getUnpublishedSubjects = ->
      subjectIds = JSON.parse localStorage.getItem('subjects')
      subjectIds = [] unless subjectIds
      _subjectIds = []
      subjects = []
      if subjectIds.length > 0
        now = Date.now()
        for sub, i in subjectIds
          return if not sub
          if now - sub.time < 1000*60*60*24*2
            _subjectIds.push {modelid: sub.modelid, time: now}
            subjects.push JSON.parse(localStorage.getItem(sub.modelid))
          else
            localStorage.removeItem(sub.modelid)

        localStorage.setItem 'subjects', JSON.stringify(_subjectIds)

      return subjects

    # 通过专题ID 获取专题详细信息
    this.getSubjectById = (id)->
      console.log "Get subject which id is #{id}"
      defer = $q.defer()
      subject = {}
      if localStorage.getItem(id)
        subject = JSON.parse(localStorage.getItem(id))
        basicInfo = angular.copy(subject)
        delete basicInfo['html']
        basicInfo.modelid = basicInfo.modelid?.slice(4)
        this.saveBasicInfo(basicInfo).then ->
          defer.resolve(subject)
      else
        url = "#{BackendUrl}special&action=getDetail&modelid=#{id}"
        $http.get(url)
          .success (data)->
            _subject = data
            html = getHtml(data.content) or ''
            html = html.replace(/<script/g, '&lt;script')
            html = html.replace(/<\/script/g, '&lt;/script')
            html = html.replace(/script>/g, 'script&gt;')
            _subject.html = html
            delete _subject.content
            defer.resolve(_subject)
            return
      return defer.promise

    # 删除本地专题
    this.deleteSubjectInLocal = deleteSubjectInLocal

    # 删除专题
    this.deleteSubjectById = (id, deleteLocal)->
      defer = $q.defer()
      deleteSubjectInLocal(id) if deleteLocal
      _url = "#{BackendUrl}special&action=del&modelid=#{id}&topicid=#{TOPICID}"
      $http.get _url
        .success (data)->
          console.log 'Delete subject in server'
          defer.resolve(data)

      return defer.promise

    # 校验专题ID是否存在
    this.checkId = (id)->
      id = window.CHANNELID + id
      defer = $q.defer()
      _url = "#{BackendUrl}special&action=checkModelid&modelid=#{id}"
      $http.get _url
        .success (data)->
          defer.resolve(data)
      return defer.promise

    # 保存专题基本信息
    this.saveBasicInfo = (basicInfo)->
      defer = $q.defer()
      _url = "#{BackendUrl}special&action=save"
      if not basicInfo.topicid
        basicInfo.topicid = window.TOPICID
      if $location.host() is 'localhost'
        defer.resolve({result: 1, modelid: basicInfo.modelid})
      else
        $http.get _url, {params: basicInfo}
          .success (data)->
            defer.resolve(data)
            return
          .error (data)->
            defer.resolve(data)
            return
      return defer.promise

    # 自动保存
    # subjects: [{modelid:1, time: createdTime},{...}]
    this.saveAutomatically = (subject)->
      console.log 'saveAutomatically'
      saveSubjectToLocal(subject)
      return

    # 提交专题
    this.upload = (subjectModel)->
      d = $q.defer()
      html = microTmpl(subjectPrototype)(subjectModel)
      html = html.replace(/&lt;/g, '<')
      html = html.replace(/&gt;/g, '>')
      html = html.replace(/&amp;/g, '&')
      _url = "#{BackendUrl}special&action=saveContent"
      $http({
        method: 'POST'
        url: _url
        data: {modelid: subjectModel.modelid_backend or subjectModel.modelid, content: html}
      }).success (data)->
        if +data.result is 1
          d.resolve(data)
          deleteSubjectInLocal(subjectModel.modelid)
        else
          alert(data.msg) if data.msg
      return d.promise

    # 预览专题
    this.preview = (subjectModel)->
      d = $q.defer()
      html = microTmpl(subjectPrototype)(subjectModel)
      html = html.replace(/&lt;/g, '<')
      html = html.replace(/&gt;/g, '>')
      $http({
        method: 'POST'
        url: "#{BackendUrl}special&action=preview"
        data:{
          modelid: subjectModel.modelid
          body: html
        }
      }).success (data)->
        d.resolve(data)
      return d.promise

    return
